/**
 * 
 */
package us.gaaoc.framework.webapp.backingbeans.attorney;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.faces.application.FacesMessage;
import javax.faces.component.UIParameter;
import javax.faces.component.UISelectOne;
import javax.faces.context.FacesContext;
import javax.faces.model.DataModel;
import javax.faces.model.ListDataModel;
import javax.faces.model.SelectItem;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.apache.myfaces.custom.fileupload.UploadedFile;
import org.hibernate.Hibernate;

import us.gaaoc.framework.businessmodel.Filing;
import us.gaaoc.framework.dao.persistenceLogic.PersistInfoIntoCaseRecord;
import us.gaaoc.framework.model.Address;
import us.gaaoc.framework.model.Attorney;
import us.gaaoc.framework.model.CaseRecord;
import us.gaaoc.framework.model.CaseRecordStatus;
import us.gaaoc.framework.model.CaseRecordType;
import us.gaaoc.framework.model.Court;
import us.gaaoc.framework.model.DocPageRange;
import us.gaaoc.framework.model.DocumentInstance;
import us.gaaoc.framework.model.DocumentPackage;
import us.gaaoc.framework.model.DocumentStatus;
import us.gaaoc.framework.model.Documents;
import us.gaaoc.framework.model.LocalCaseCategory;
import us.gaaoc.framework.model.LocalCaseDivision;
import us.gaaoc.framework.model.LocalCaseFilingType;
import us.gaaoc.framework.model.LocalCaseType;
import us.gaaoc.framework.model.Organizations;
import us.gaaoc.framework.model.Person;
import us.gaaoc.framework.model.PersonAddress;
import us.gaaoc.framework.model.PersonParticipants;
import us.gaaoc.framework.util.DateUtil;
import us.gaaoc.framework.util.LocalCaseInformation;
import us.gaaoc.framework.util.ValidatingTextFile;
import us.gaaoc.framework.util.io.FileUtility;
import us.gaaoc.framework.util.pdf.Concatenate;
import us.gaaoc.framework.util.pdf.PageRangesFromTextTargetsUtility;
import us.gaaoc.framework.util.pdf.SplitPDF;
import us.gaaoc.framework.webapp.backingbeans.BaseBackingBean;
import us.gaaoc.framework.webapp.util.UploadPackageUtility;

/**
 * @author Sukahda Tapshalkar Mar 26, 2007
 * 
 */
@SuppressWarnings({"unchecked", "deprecation"})
public class FilingDocumentUploadPage extends BaseBackingBean {

	/** Generated Serial Version UID */
	private static final long serialVersionUID = -60848976107909141L;

	/**
	 * Properties
	 */
	private CaseRecord cr;

	private Date courtDate;

	private DataModel personModel;

	private DataModel documentsModel;

	private UploadedFile myFile;

	private List<UploadedFile> myFilesList = null;

	private List<Documents> documentList = new ArrayList<Documents>();

	private List<Documents> newUploadedDocumentList = new ArrayList<Documents>();

	private Filing filing;

	private List<Documents> uploadedDocumentList;

	private DataModel myFilesModel;

	private DataModel establishmentFilingModel;

	private UISelectOne docTypeInput;

	private ArrayList<SelectItem> docTypeDescriptionsItems;

	private boolean renderReviewBtn;

	private String docType;

	private UIParameter documentClicked;

	private UIParameter caseDetailsPage;

	private boolean renderListOfPersonsBtn;

	private List<Person> personsExtractedFromTextList = new ArrayList<Person>();

	private Person cusPerson;

	private PersonAddress cusPersonAddress;
	private Address cusAddress;

	private Person nonCusPerson;

	private PersonAddress nonCusPersonAddress;
	private Address nonCusAddress;

	private List<Person> initiatingPartyPersonsList = new ArrayList<Person>();

	private List<PersonAddress> initiatingPartyPersonAddresses = new ArrayList<PersonAddress>();

	// added by Sukhada for uploading packages
	private String packageType;
	private UISelectOne packageTypeInput;
	private ArrayList<SelectItem> packageTypeDescriptionsItems = new ArrayList<SelectItem>();
	private UploadedFile packageDoc;
	private Court court;

	// added by Michael Alexandrou to capture the local system's tracking of
	// defendants
	private String externalCaseRecordNumber;

	// added by Michael Alexandrou to capture the social security numbers
	// and the dates of birth for checking for duplicate persons
	private String cusSSN;

	private String nonCusSSN;

	private List<String> initiatingPartyPersonSSNList;
	
	private String courtUuid;

	/**
	 * Integer to hold the external case category code.
	 * <p>
	 * External Case Category Codes: <br/> 1 = Establishment, OCSS <br/> 2 =
	 * Contempt, OCSS <br/> 3 = Review/Modification, OCSS <br/> 4 = Motion to
	 * Redirect, OCSS <br/> 5 = Motion to Transfer, OCSS <br/> 6 = Registration,
	 * OCSS <br/>
	 * </p>
	 */
	int externalCaseCategoryCode = 0;

	private static final Logger LOG = Logger
			.getLogger(FilingDocumentUploadPage.class);

	/**
	 * Constructor
	 * 
	 */
	public FilingDocumentUploadPage() {
		Map sessionMap = this.getFacesContext().getExternalContext()
				.getSessionMap();

		String crUuid = (String) sessionMap.get("caseUuid");
		courtUuid = (String) sessionMap.get("courtUuid");
		
		Court courtFromSession = this.getModelFacade().findCourt(courtUuid);
		this.setCourt(courtFromSession);
		/*
		 * TODO If existing case, pull external case category code from
		 * database. If new case, pull case category code from parameter set on
		 * new filing page in session.
		 */
		/***********************************************************************
		 * External Case Category Codes: 1 = Establishment, OCSS 2 = Contempt,
		 * OCSS 3 = Review/Modification, OCSS 4 = Motion to Redirect, OCSS 5 =
		 * Motion to Transfer, OCSS 6 = Registration, OCSS
		 * ********************************************************************
		 */
		externalCaseCategoryCode = (Integer) sessionMap
				.get("externalCaseCategoryCode");
		if (crUuid != null) {
			this.setRenderReviewBtn(true);
			this.setRenderListOfPersonsBtn(true);
			this.setCr(this.getModelFacade().findCaseRecordById(crUuid, courtUuid));
		} else {
			this.setRenderReviewBtn(false);
			this.setRenderListOfPersonsBtn(false);
		}
	}

	/**
	 * @return the docType
	 */
	public String getDocType() {
		return docType;
	}

	/**
	 * @param docType
	 *            the docType to set
	 */
	public void setDocType(String docType) {
		this.docType = docType;
	}

	public UISelectOne getDocTypeInput() {
		return docTypeInput;
	}

	public void setDocTypeInput(UISelectOne docTypeInput) {
		this.docTypeInput = docTypeInput;
	}

	/**
	 * @return docTypeDescriptionsItems
	 */
	public ArrayList<SelectItem> getDocTypeDescriptionsItems() {
		// Initialize Array List if null
		if (docTypeDescriptionsItems == null) {
			docTypeDescriptionsItems = new ArrayList<SelectItem>();
		}
		List<DocumentInstance> docTypeList = this.getModelFacade()
				.findDocumentInstanceByAliasType(court);
		int i = docTypeList.size();
		DocumentInstance dt;
		for (int j = 0; j < i; j++) {
			dt = docTypeList.get(j);
			docTypeDescriptionsItems.add(new SelectItem(new Integer(dt
					.getCode()).toString(), dt.getDescription()));
		}
		return docTypeDescriptionsItems;
	}

	public void setDocTypDescriptionsItems(ArrayList<SelectItem> si) {
		docTypeDescriptionsItems = si;
	}

	/**
	 * @return myFilesModel
	 */
	public DataModel getMyFilesModel() {
		return myFilesModel;
	}

	/**
	 * @param set
	 *            myFilesModel
	 */
	public void setMyFilesModel(DataModel myFilesModel) {
		this.myFilesModel = myFilesModel;
	}

	/**
	 * @return myFilesList
	 */
	public List<UploadedFile> getMyFilesList() {
		return myFilesList;
	}

	/**
	 * @param set
	 *            myFile
	 */
	public void setMyFiles(List<UploadedFile> myFilesList) {
		this.myFilesList = myFilesList;
	}

	/**
	 * @return the myFile
	 */
	public UploadedFile getMyFile() {
		return myFile;
	}

	/**
	 * @param myFile
	 *            the myFile to set
	 */
	public void setMyFile(UploadedFile myFile) {
		this.myFile = myFile;
	}

	/**
	 * @return the courtDate
	 */
	public Date getCourtDate() {
		return courtDate;
	}

	/**
	 * @param courtDate
	 *            the courtDate to set
	 */
	public void setCourtDate(Date courtDate) {
		this.courtDate = courtDate;
	}

	/**
	 * @return documentList
	 */
	public List<Documents> getDocumentList() {
		return documentList;
	}

	/**
	 * @param set
	 *            DocumentTypesByAlias documentList
	 */
	public void setDocumentList(List<Documents> documentList) {
		this.documentList = documentList;
	}

	/**
	 * @return documentsModel
	 */
	public DataModel getDocumentsModel() {
		return documentsModel;
	}

	/**
	 * @param set
	 *            documentsModel
	 */
	public void setDocumentsModel(DataModel documentsModel) {
		this.documentsModel = documentsModel;
	}

	/**
	 * @return personModel
	 */
	public DataModel getPersonModel() {
		return personModel;
	}

	/**
	 * @param set
	 *            personModel
	 */
	public void setPersonModel(DataModel personModel) {
		this.personModel = personModel;
	}

	/**
	 * @return the documentClicked
	 */
	public UIParameter getDocumentClicked() {
		return documentClicked;
	}

	/**
	 * @param documentClicked
	 *            the documentClicked to set
	 */
	public void setDocumentClicked(UIParameter documentClicked) {
		this.documentClicked = documentClicked;
	}

	/**
	 * @return the packageType
	 */
	public String getPackageType() {
		return packageType;
	}

	/**
	 * @param packageType
	 *            the packageType to set
	 */
	public void setPackageType(String packageType) {
		this.packageType = packageType;
	}

	/**
	 * @return the packageTypeDescriptionsItems
	 */
	public ArrayList<SelectItem> getPackageTypeDescriptionsItems() {
		
		// Reinitialization of array to avoid duplicate additions to list.
		

		packageTypeDescriptionsItems = new ArrayList<SelectItem>();
		System.out.println("The Court ID now in process is" + court.getUuid());
		if(court.getUuid().equalsIgnoreCase("courtUuidCoweta"))
		{
			List<DocumentPackage> packageTypeList = this.getModelFacade().findDocumentPackageByCaseRecordAction(court,this.getModelFacade().getCaseRecordActionsById(externalCaseCategoryCode));
			for (DocumentPackage dp : packageTypeList) {
				packageTypeDescriptionsItems.add(new SelectItem(dp.getUuid(), dp
						.getPackageName()));
				LOG.info("The package is .." + dp.getPackageName());
			}
			
			return packageTypeDescriptionsItems;
		}
		else
		{
			List<DocumentPackage> packageTypeList = this.getModelFacade().findDocumentPackageByAliasType(court);
			for (DocumentPackage dp : packageTypeList) {
				packageTypeDescriptionsItems.add(new SelectItem(dp.getUuid(), dp
						.getPackageName()));
				LOG.info("The package is .." + dp.getPackageName());
			}
			
			return packageTypeDescriptionsItems;
		}
		
		
	}

	/**
	 * @param packageTypeDescriptionsItems
	 *            the packageTypeDescriptionsItems to set
	 */
	public void setPackageTypeDescriptionsItems(
			ArrayList<SelectItem> packageTypeDescriptionsItems) {
		this.packageTypeDescriptionsItems = packageTypeDescriptionsItems;
	}

	/**
	 * @return the packageTypeInput
	 */
	public UISelectOne getPackageTypeInput() {
		return packageTypeInput;
	}

	/**
	 * @param packageTypeInput
	 *            the packageTypeInput to set
	 */
	public void setPackageTypeInput(UISelectOne packageTypeInput) {
		this.packageTypeInput = packageTypeInput;
	}

	/**
	 * @return the packageDoc
	 */
	public UploadedFile getPackageDoc() {
		return packageDoc;
	}

	/**
	 * @param packageDoc
	 *            the packageDoc to set
	 */
	public void setPackageDoc(UploadedFile packageDoc) {
		this.packageDoc = packageDoc;
	}

	/**
	 * @return the court
	 */
	public Court getCourt() {
		return court;
	}

	/**
	 * @param court
	 *            the court to set
	 */
	public void setCourt(Court court) {
		this.court = court;
	}

	/**
	 * upload the document and create case record.
	 * 
	 * @return
	 * @throws Exception
	 *             DocumentTypesByAlias
	 */
	public String uploadFile() throws Exception {
		String returnStr = null;
		Map sessionMap = this.getFacesContext().getExternalContext()
				.getSessionMap();
		String caseRecordUuid = (String) sessionMap.get("caseUuid");
		String courtUuid = (String) sessionMap.get("courtUuid");
		Court court = this.getModelFacade().findCourt(courtUuid);

		// TODO Need to either replace writing to disk with an in memory object
		// or need to use the FileUtility class for writing to disk.
		byte[] fileBytes = (byte[]) myFile.getBytes();
		//String fileName = myFile.getName();
		InputStream inStream = myFile.getInputStream();
		if (caseRecordUuid != null) { // case record already created
			this
					.setCr(this.getModelFacade().findCaseRecordById(
							caseRecordUuid, courtUuid));
			if (myFile.getContentType().equalsIgnoreCase("application/pdf")) {
				if (this.getDocType().equalsIgnoreCase("DATA FILE")) {
					LOG.info("Inside the checking of the title of the pdf..");
					FacesContext facesContext = FacesContext
							.getCurrentInstance();
					facesContext
							.addMessage(
									"uploadPackageForm:uploadPack",
									new FacesMessage(
											"DATA FILE is not a title of a pdf's allowed for upload "));
					return "upload";
				}
				Documents doc = new Documents();
				
				DocumentInstance documentInstance = this.getModelFacade()
						.findDocumentInstanceByCode(
								Integer.parseInt(this.docType));
				DocumentStatus ds = new DocumentStatus();
				ds = this.getModelFacade().findDocumentStatus(6);
				Person personSigned = (Person) sessionMap.get("person");
				String tempTitle = documentInstance.getDescription();
				doc
						.setTitle(tempTitle.replace(' ', '_')
								.replace(",_", "_").replace('-', '_').replace(
										':', '_').replace('\'', '_'));
				
				doc.setPhysicalType("pdf");
				doc.setDocumentInstance(documentInstance);
				doc.setReceivedDateTime(DateUtil.getCurrentDate());
				doc.setStatus(ds);
				doc.setPerson(personSigned);
				CaseRecord cr = this.getModelFacade().findCaseRecordById(
						caseRecordUuid, courtUuid);
				doc.setCaseRecord(cr);
				List<Documents> listOfDoc = new ArrayList<Documents>();
				listOfDoc = this.getModelFacade().findDocumentsByCaseUuid(
						caseRecordUuid);		
				for (Documents d : listOfDoc) {
					/*
					 * Check if the document is already in list and it is not
					 * the existing i.e. imported If it is already in the list
					 * and not imported then replace/ delete the document from
					 * the list otherwise do not do anything.
					 */
					if (d.getDocumentInstance().getDocumentType().getCode() == (doc
							.getDocumentInstance().getDocumentType().getCode())
							&& d.getStatus().getCode() == 6) {
						this.getModelFacade().deleteDocument(d);
					}
				}
				this.getModelFacade().makePersistent(doc);
				
				doc.setContent(null,fileBytes);

				returnStr = "upload";

			} else { // not a pdf file
				FacesContext facesContext = FacesContext.getCurrentInstance();
				facesContext
						.addMessage(
								"uploadForm:uploadFile",
								new FacesMessage(
										"A text file has been already uploaded. Please upload a pdf file if there's any. "));
				returnStr = "failure";
			}
		} else { // no case record has been created yet.
			if ((myFile.getContentType()
					.equalsIgnoreCase("text/x-comma-separated-values"))
					|| (myFile.getContentType()
							.equalsIgnoreCase("application/msword"))) {
				// it's a new data file
				ValidatingTextFile validate = new ValidatingTextFile();
				// boolean validateTextFile =
				// validate.validateTextFile(newFile);
				boolean validateTextFile = validate.validateTextFile(inStream,this.externalCaseCategoryCode);
				if (!validateTextFile) {
					FacesContext facesContext = FacesContext
							.getCurrentInstance();
					facesContext.addMessage("uploadForm:uploadFile",
							new FacesMessage(" Text File: Invalid format"));

					return "failure";
				} else {// text file is of valid format
					FacesContext facesContext = FacesContext
							.getCurrentInstance();
					facesContext
							.addMessage(
									"uploadForm:uploadFile",
									new FacesMessage(
											" Data File: Valid format. Deleting the Data File will result in deleting"
													+ " the initial filing and all the pdf's associated with it  "));

					//this.courtDate = validate.validateCourtDate();
					//if (this.courtDate != null) {
					//	LOG.info("The court date is .."
					//			+ this.courtDate.getDay());
					//}
					this.courtDate = validate.courtDate;
					/*
					this.cusPerson = validate.getCusPerson();
					this.nonCusPerson = validate.getNonCusPerson();
					this.initiatingPartyPersonsList = validate
							.getInitiatingPartyPersonsList();
					this.cusPersonAddress = validate.getCusPersonAddress();
					this.nonCusPersonAddress = validate
							.getNonCusPersonAddress();
					this.externalCaseRecordNumber = validate
							.extractExternalCaseRecordNumber();
					PersistInfoIntoCaseRecord picr = new PersistInfoIntoCaseRecord();
					this.cusSSN = validate.extractCustodianSSN();
					this.nonCusSSN = validate.extractNonCustodianSSN();
					this.initiatingPartyPersonSSNList = validate
							.getInitiatingPartyPersonSSNList();
*/
					this.setCusPerson(validate.getCusPerson());
					this.setNonCusPerson(validate.getNonCusPerson());
					this.setInitiatingPartyPersonsList(validate.getInitiatingPartyPersonsList());
					this.setCusPersonAddress(validate.getCusPersonAddress());
					this.setNonCusPersonAddress(validate.getNonCusPersonAddress());
					this.setExternalCaseRecordNumber(validate.getExternalCaseRecordNumber());
					this.setCusSSN(validate.getCustodianSSN());
					this.setNonCusSSNHashed(validate.getNonCustodianSSN());
					this.setInitiatingPartyPersonSSNList(validate.getInitiatingPartyPersonSSNList());
					// this.cusDateOfBirth =
					// validate.extractCustodianDateOfBirth(newFile);

					// this.nonCusDateOfBirth =
					// validate.extractNonCustodianDateOfBirth(newFile);

					// this.initiatingPartyPersonDateOfBirthList =
					// validate.getInitiatingPartyPersonDateOfBirthList();

					sessionMap.put("externalCaseRecordNumber",
							this.externalCaseRecordNumber);
					LOG.info("external case number is .."
							+ this.getExternalCaseRecordNumber());

					this.setRenderListOfPersonsBtn(true);
					this.setRenderReviewBtn(true);
				
					PersistInfoIntoCaseRecord picr = new PersistInfoIntoCaseRecord();
					
					CaseRecord caseRecord = picr.createCaseRecord(court, this.externalCaseCategoryCode);
				
					Person filer = (Person) this.getFacesContext()
						.getExternalContext().getSessionMap().get("person");
					
					/* TODO - This needs to be updated when persons are associated
					 * with more than one organization to pull based on role in the
					 * organization.  This should be pulled based on what organization
					 * this person is filing the document for.
					 *
					 * Attorney's can file on behalf of multiple orgainizations.
					 */
					
					/* TODO - This section will have to be redone to when filing
					 * in from the respondant party.  For the current time, it 
					 * is set up this way for OCSS as they are always the 
					 * initiating party for Child Support Cases. 
					 */
					//String orgUuid = "initiatingPartyOrganizationUuid";
					Attorney filingAttorney = this.getModelFacade()
						.findAttorneyByPerson(filer);
					String initiatingPartyOrgUuid = filingAttorney
						.getOrganization().getUuid();
					LOG.debug("Filer's Organizational UUID = " 
							+ initiatingPartyOrgUuid);
					Organizations org = this.getModelFacade()
							.findOrganizationById(initiatingPartyOrgUuid);
					LOG.info("the organization is ...." + org.getName());
					this.setCr(caseRecord);
					// call the PersistInfoIntoCaseRecord
					// PersistInfoIntoCaseRecord persist = new
					// PersistInfoIntoCaseRecord();
					// ParsingTextFile parseTextFile = new ParsingTextFile();
					
					Person personSigned = (Person) sessionMap.get("person");
					picr.persistExtractedInfoFromTextFile(personSigned, caseRecord,
							this.cusPerson, this.cusSSN, this.nonCusPerson,
							this.nonCusSSN, this.cusAddress,
							this.nonCusAddress,
							this.initiatingPartyPersonsList,
							this.initiatingPartyPersonAddresses,
							this.initiatingPartyPersonSSNList,
							initiatingPartyOrgUuid);

					/*
					 * this.insertTextFile(caseRecord, this.cusPerson,
					 * this.nonCusPerson, this.cusPersonAddress,
					 * this.nonCusPersonAddress,
					 * this.initiatingPartyPersonsList,
					 * this.initiatingPartyPersonAddresses);
					 */
					// Record the newly created case record with the extracted
					// OCSS case number
					if (this.externalCaseRecordNumber != null) {
						this
								.getModelFacade()
								.insertIntoCaseRecordIdExternalCaseRecordNumber(
										caseRecord,
										this.externalCaseRecordNumber, org);
					}
					Documents doc = new Documents();
					DocumentInstance di = this.getModelFacade()
							.findDocumentInstanceByCode(
									Integer.parseInt(this.getDocType()));
					DocumentStatus ds = new DocumentStatus();
					ds = this.getModelFacade().findDocumentStatus(6);
					doc.setTitle("DATA FILE");
					doc.setContent(null,fileBytes);
					doc.setPhysicalType("text");
					doc.setDocumentInstance(di);
					doc.setReceivedDateTime(DateUtil.getCurrentDate());
					doc.setStatus(ds);
			//		Person personSigned = (Person) sessionMap.get("person");
					doc.setPerson(personSigned);
					doc.setCaseRecord(caseRecord);
					this.getModelFacade().makePersistent(doc);
					// commit the transaction
					//HibernatePhaseListener.getSessionFactory().getCurrentSession().getTransaction().commit();
					sessionMap.put("caseUuid", caseRecord.getUuid());
					returnStr = "upload";
				}
			} else { // not a data file
				FacesContext facesContext = FacesContext.getCurrentInstance();
				facesContext.addMessage("uploadForm:uploadFile",
						new FacesMessage(" Please upload a data file first "));
				returnStr = "failure";
			}
		}
		return returnStr;
	}

	/**
	 * This method navigates user to the Case Details Page
	 * 
	 * @return String
	 */
	public String gotoCaseDetailsPage() {
		Map sessionMap = this.getFacesContext().getExternalContext()
				.getSessionMap();
		sessionMap.put("from", "establishmentFilingPage");
		return "gotoCaseDetailsPage";
	}

	public String retrieveFilingsForExternalCaseNumber() {
		return "goToSearchPage";
	}

	public String uploadPackage() throws Exception {

		Map sessionMap = this.getFacesContext().getExternalContext()
				.getSessionMap();
		String caseRecordUuid = (String) sessionMap.get("caseUuid");
		// case record already created
		DocumentPackage docPackage = this.getModelFacade()
			.findPackageNameByUuid(this.packageType);
		Person personSigned = (Person) sessionMap.get("person");
		
		try {
			UploadPackageUtility.uploadPackage(this.getCourt(),
					caseRecordUuid,
					packageDoc,
					docPackage,
					personSigned,
					this.getUploadedDocumentList(),
					this.getModelFacade());
			FacesContext facesContext = FacesContext.getCurrentInstance();
			facesContext.addMessage("uploadPackageForm:uploadPack",
					new FacesMessage(" Package is Uploaded and Splitted"));

		}catch(Exception exn)
		{
			FacesContext facesContext = FacesContext.getCurrentInstance();
			facesContext.addMessage("uploadPackageForm:uploadPack", new FacesMessage("Error: " + exn.getMessage()));
			exn.printStackTrace();			
		}
				
		return "upload";
	}

	public String ViewUploadedFileInformation() {
		this.documentList = this.getModelFacade().findDocumentsByDocStatusCode(
				6);
		documentsModel = new ListDataModel();
		documentsModel.setWrappedData(documentList);
		return "viewUploadedFileInformation";
	}

	/*
	 * not using  
	 *
	public void viewListOfUploadedFiles() {
		// To avoid duplicate additions to arrays, reinitialize with each call.
		uploadedDocumentList = new ArrayList<Documents>();
		documentList = new ArrayList<Documents>();
		Map sessionMap = this.getFacesContext().getExternalContext()
				.getSessionMap();
		String uuid = (String) sessionMap.get("caseUuid");
		this.documentList = this.getModelFacade().findDocumentsByCaseUuid(uuid);
		for (Documents doc : documentList) {
			/*
			if (doc.getStatus().getDescription().equalsIgnoreCase("upload")) {
				LOG.info("Adding the document " + doc.getTitle()
						+ " to the uploaded dcoument list");
						*
			if ((doc.getStatus().getCode()==6)					//upload 
					|| (doc.getStatus().getCode() == 15)) {		//failedAttorneySignature
				LOG.info("Adding the document " + doc.getTitle()
						+ " to the uploaded dcoument list");
			
				this.uploadedDocumentList.add(doc);

			}
		}
	}
*/
	/**
	 * @return the uploadedDocumentList
	 */
	public List<Documents> getUploadedDocumentList() {
		// To avoid duplicate additions to array, reinitialize with each call.
		uploadedDocumentList = new ArrayList<Documents>();
		documentList = new ArrayList<Documents>();
		Map sessionMap = this.getFacesContext().getExternalContext()
				.getSessionMap();
		String uuid = (String) sessionMap.get("caseUuid");
		if (uuid != null) {
			List<Documents> documentList = this.getModelFacade()
					.findDocumentsByCaseUuid(uuid);
			for (Documents doc : documentList) {
				//if (doc.getStatus().getDescription().equalsIgnoreCase("upload")) {
				//We want to show all the documents when modifying the filing
				int docCode = doc.getStatus().getCode(); // 6 == upload, 8 == signedByClerk, 11 == signedByAttorney, 15== failedAttorneySignature
				if (docCode == 6 || docCode == 8 || docCode == 11 ||docCode == 15 || (docCode > 10 && docCode < 16)) {
					if ((doc.getStatus().getCode()==6)					//upload 
							|| (doc.getStatus().getCode() == 15) ||  (docCode > 10 && docCode < 16)) {		//failedAttorneySignature
						LOG.info("Adding the document " + doc.getTitle()
								+ " to the uploaded dcoument list");
						this.uploadedDocumentList.add(doc);
						}
				}
			}
		}		return uploadedDocumentList;
	}

	/**
	 * @param uploadedDocumentList
	 *            the uploadedDocumentList to set
	 */
	public void setUploadedDocumentList(List<Documents> uploadedDocumentList) {
		this.uploadedDocumentList = uploadedDocumentList;
	}
	
	public String viewFile() {
		FacesContext context = this.getFacesContext();
		HttpServletResponse resp = (HttpServletResponse) FacesContext
				.getCurrentInstance().getExternalContext().getResponse();
		Documents doc = (Documents) this.getDocumentClicked().getValue();
		String docTitle = (String) doc.getTitle();
		byte[] docContent = doc.getContent();
		try {
			FileUtility.streamReportToBrowser(resp, docTitle, docContent);
		} catch (IOException e) {
			LOG.error("Error in CaseDetailPage.viewFile() method: " + e);
		}
		context.responseComplete();
		return "stay";
	}

	public String reviewOfFiling() {
		LOG.info("Inside the reviewOfFiling method....");
		return "reviewOfFiling";
	}

	public CaseRecord getCr() {
		return cr;
	}

	public void setCr(CaseRecord cr) {
		this.cr = cr;
	}

	public List<Documents> getNewUploadedDocumentList() {
		return newUploadedDocumentList;
	}

	public void setNewUploadedDocumentList(
			List<Documents> newUploadedDocumentList) {
		this.newUploadedDocumentList = newUploadedDocumentList;
	}

	public UIParameter getCaseDetailsPage() {
		return caseDetailsPage;
	}

	public void setCaseDetailsPage(UIParameter caseDetailsPage) {
		this.caseDetailsPage = caseDetailsPage;
	}

	public DataModel getEstablishmentFilingModel() {
		return establishmentFilingModel;
	}

	public void setEstablishmentFilingModel(DataModel establishmentFilingModel) {
		this.establishmentFilingModel = establishmentFilingModel;
	}

	public Filing getFiling() {
		return filing;
	}

	public void setFiling(Filing filing) {
		this.filing = filing;
	}

	public String deleteDocument() {
		LOG.info("Inside the deleteDocument..");
		Map sessionMap = this.getFacesContext().getExternalContext()
				.getSessionMap();
		Documents doc = (Documents) this.getDocumentClicked().getValue();
		CaseRecord cr = this.getCr();
		String extention = doc.getPhysicalType();
		if (extention.equalsIgnoreCase("text")) {
			List<PersonParticipants> ppList = this.getModelFacade()
					.getPersonParicipant(cr);
			for (PersonParticipants pp : ppList) {
				Person personParticipant = (Person) this.getModelFacade()
						.findPersonbyID(pp.getPerson().getUuid());
				List<CaseRecord> crList = this.getModelFacade()
						.findCaseRecordsByPerson(personParticipant);
				LOG.info("List of related case Records for the PP "
						+ crList.size());
				if ((personParticipant.getRoles().isEmpty())
						&& (crList.size() <= 1)) {
					this.getModelFacade().deletePerson(pp.getPerson());

				} else {
					this.getModelFacade().deletePersonParticipants(pp);
				}
			}
			this.getModelFacade().deleteCaseRecord(this.getCr().getUuid(), courtUuid);
			sessionMap.remove("caseUuid");
		}

		this.getModelFacade().enableDocDeleteFlag(doc);
		this.getModelFacade().deleteDocument(doc);
		// commit the transaction
		// Removed on 2007-07-16 to fix error from loss of session/transaction
		// after deletion of document.
		// b7006e6c-695c-11dd-945f-00301b45ff56
		// HibernatePhaseListener.getSessionFactory().getCurrentSession()
		// .getTransaction().commit();
		return "upload";
	}

	public String back() {
		Map sessionMap = this.getFacesContext().getExternalContext()
				.getSessionMap();
		sessionMap.remove("caseUuid");
		return "back";
	}

	public boolean isRenderReviewBtn() {
		return renderReviewBtn;
	}

	public void setRenderReviewBtn(boolean renderReviewBtn) {
		this.renderReviewBtn = renderReviewBtn;
	}

	public boolean validateAttorney(Person personAttorney) {
		// Attorney attorney = this.getModelFacade().

		return false;
	}

	public boolean isRenderListOfPersonsBtn() {
		return renderListOfPersonsBtn;
	}

	public void setRenderListOfPersonsBtn(boolean renderListOfPersonsBtn) {
		this.renderListOfPersonsBtn = renderListOfPersonsBtn;
	}

	public List<Person> getPersonsExtractedFromTextList() {
		return personsExtractedFromTextList;
	}

	public void setPersonsExtractedFromTextList(
			List<Person> personsExtractedFromTextList) {
		this.personsExtractedFromTextList = personsExtractedFromTextList;
	}

	public Person getCusPerson() {
		return cusPerson;
	}

	public void setCusPerson(Person cusPerson) {
		this.cusPerson = cusPerson;
	}

	public PersonAddress getCusPersonAddress() {
		return cusPersonAddress;
	}

	public void setCusPersonAddress(PersonAddress cusPersonAddress) {
		this.cusPersonAddress = cusPersonAddress;
	}

	public Person getNonCusPerson() {
		return nonCusPerson;
	}

	public void setNonCusPerson(Person nonCusPerson) {
		this.nonCusPerson = nonCusPerson;
	}

	public PersonAddress getNonCusPersonAddress() {
		return nonCusPersonAddress;
	}

	public void setNonCusPersonAddress(PersonAddress nonCusPersonAddress) {
		this.nonCusPersonAddress = nonCusPersonAddress;
	}

	public List<Person> getInitiatingPartyPersonsList() {
		return initiatingPartyPersonsList;
	}

	public void setInitiatingPartyPersonsList(
			List<Person> initiatingPartyPersonsList) {
		this.initiatingPartyPersonsList = initiatingPartyPersonsList;
	}

	public List<PersonAddress> getInitiatingPartyPersonAddresses() {
		return initiatingPartyPersonAddresses;
	}

	public void setInitiatingPartyPersonAddresses(
			List<PersonAddress> initiatingPartyPersonAddresses) {
		this.initiatingPartyPersonAddresses = initiatingPartyPersonAddresses;
	}

	/**
	 * 
	 * @param documentInstance
	 * @param newFile
	 * @param caseRecordUuid
	 * @param personSigned
	 * @throws IOException
	 */

	private void splitPDFPackage(DocumentPackage documentPackage, File newFile,
			String caseRecordUuid, Person personSigned) throws IOException {
		// HibernatePhaseListener.getSessionFactory().getCurrentSession()
		// .getTransaction().begin();
		DocumentStatus ds = new DocumentStatus();
		ds = this.getModelFacade().findDocumentStatus(6);

		// Pull List of Documents and Page Ranges from DB
		List<DocPageRange> dprList = this.getModelFacade()
				.findAllPageRangeByPackageUuid(documentPackage);

		/*
		 * Check the document for dynamically set page range indicators.
		 * 
		 * If present, over ride page ranges from the database. If not present,
		 * then leave list of documents and page ranges unchanged.
		 */
		PageRangesFromTextTargetsUtility targetBasedRangeChecker = new PageRangesFromTextTargetsUtility();

		/*
		 * TODO Check memory requirements of files and potentially change from
		 * file based passing to in memory objects
		 */
		// Convert file to Byte Array
		// FileInputStream fis = convertFileToInputStream(newFile);
		FileInputStream fis = FileUtility.convertFileToInputStream(newFile);

		List<DocPageRange> dprUpdatedList = targetBasedRangeChecker
				.pageRangesFromTargetsCheck(fis, dprList);
		for (DocPageRange dpr : dprUpdatedList) {
			Hibernate.initialize(
					dpr.getDocumentInstance()
					);
		}

		SplitPDF sp = new SplitPDF();

		ByteArrayOutputStream[] baosArray = sp.SplitFile("C:" + File.separator + "temp" + File.separator + newFile.getName(), dprUpdatedList);
		// sp.SplitFile( fis, dprUpdatedList);
		int i = 0;

		for (DocPageRange dn : dprUpdatedList) { // Commented out PDFList
			Documents tempDoc = new Documents();
			
			DocumentInstance docInstance = new DocumentInstance();
			docInstance = dn.getDocumentInstance();

			// String fileTitle =
			// (dn.getDocumentInstance().getDescription().toString().replace('
			// ', '_').replace('-','_').replace(':', '_').replace('\'','+'));
			String fileTitle = (dn.getDocumentInstance().getDescription()
					.toString().replace(' ', '_').replace("-", "_").replace(
							",_", "_").replace(':', '_').replace('\'', '_'));

			tempDoc.setTitle(fileTitle);
			tempDoc.setPhysicalType("pdf");
			CaseRecord cr = this.getModelFacade().findCaseRecordById(
					caseRecordUuid, courtUuid);
			tempDoc.setCaseRecord(cr);
			tempDoc.setDocumentInstance(docInstance);
			tempDoc.setPerson(personSigned);
			tempDoc.setReceivedDateTime(DateUtil.getCurrentDate());
			tempDoc.setStatus(ds);
			
			this.getModelFacade().makePersistent(tempDoc);


			byte[] docContent = baosArray[i].toByteArray();
			tempDoc.setContent(null,docContent);

			List<Documents> listOfDoc = new ArrayList<Documents>();
			listOfDoc = this.getModelFacade().findDocumentsByCaseUuid(
					caseRecordUuid);
			for (Documents d : listOfDoc) {
				/*
				 * if
				 * (d.getDocumentInstance().getDocumentType().getCode().equals(
				 * tempDoc.getDocumentInstance().getDocumentType() .getCode())) {
				 * this.getModelFacade().deleteDocument(d); }
				 */

				if (d.getDocumentInstance().getCode() == (tempDoc
						.getDocumentInstance().getCode())
						&& d.getStatus().getCode() == 6) {
					this.getModelFacade().deleteDocument(d);
				}
			}
			// file.delete();
			
			i++;
		}
		// HibernatePhaseListener.getSessionFactory().getCurrentSession()
		// .getTransaction().commit();
	}
	
	public String getExternalCaseRecordNumber() {
		return this.externalCaseRecordNumber;
	}

	public void setExternalCaseRecordNumber(String externalCaseRecordNumber) {
		this.externalCaseRecordNumber = externalCaseRecordNumber;
	}

	public String getCusSSN() {
		return cusSSN;
	}

	public void setCusSSN(String cusSSN) {
		this.cusSSN = cusSSN;
	}

	public String getNonCusSSNHashed() {
		return nonCusSSN;
	}

	public void setNonCusSSNHashed(String nonCusSSNHashed) {
		this.nonCusSSN = nonCusSSNHashed;
	}

	public List<String> getInitiatingPartyPersonSSNList() {
		return initiatingPartyPersonSSNList;
	}

	public void setInitiatingPartyPersonSSNList(
			List<String> initiatingPartyPersonSSNList) {
		this.initiatingPartyPersonSSNList = initiatingPartyPersonSSNList;
	}

	/**
	 * @return the cusAddress
	 */
	public Address getCusAddress() {
		return cusAddress;
	}

	/**
	 * @param cusAddress the cusAddress to set
	 */
	public void setCusAddress(Address cusAddress) {
		this.cusAddress = cusAddress;
	}

	/**
	 * @return the nonCusAddress
	 */
	public Address getNonCusAddress() {
		return nonCusAddress;
	}

	/**
	 * @param nonCusAddress the nonCusAddress to set
	 */
	public void setNonCusAddress(Address nonCusAddress) {
		this.nonCusAddress = nonCusAddress;
	}

}